package com.yawn.zk.controller;

import com.yawn.zk.client.ZkClient;
import org.apache.curator.framework.api.transaction.CuratorTransaction;
import org.apache.curator.framework.api.transaction.CuratorTransactionResult;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("zk")
public class TestZkController {

    @Autowired
    private ZkClient zkClient;

    @GetMapping("t1")
    public String test1() {
        if (zkClient.isExistNode("/com")) {
            zkClient.deleteChildrenIfNeededNode("/com");
//            zkClient.deleteNode("/com"); // 删除叶子节点
        }
        zkClient.createNode("/com", CreateMode.PERSISTENT, null);
        zkClient.createNode("/com/yawn", CreateMode.EPHEMERAL, "lala");
        zkClient.createNode("/com/yawn2", CreateMode.EPHEMERAL, "lala2");
        zkClient.createNode("/com/yawn3", CreateMode.EPHEMERAL, "lala3");
        zkClient.createNode("/com/yawn4", CreateMode.EPHEMERAL, "lala4");
        List<String> children = zkClient.getChildren("/com");
        System.out.println(children);
        String data = zkClient.getNodeData("/com/yawn");
        System.out.println(data);
        zkClient.registerWatcherNodeChanged("/com/yawn2",
                () -> System.out.println("/com/yawn2节点的值变化为：" + zkClient.getNodeData("/com/yawn2"))
        );
        boolean b = zkClient.updateNodeData("/com/yawn2", "alal");
        System.out.println(b);
        data = zkClient.getNodeData("/com/yawn2");
        System.out.println(data);
        zkClient.deleteNode("/com/yawn2");
        return "okay!";
    }

    @GetMapping("tx")
    public String tx() throws Exception {
        Collection<CuratorTransactionResult> results = zkClient.startTransaction().create().forPath("/aaa")
                .and().create().forPath("/aaa/bbb")
                .and().create().forPath("/aaa/ccc")
                .and().commit();
        System.out.println(results);
        Collection<CuratorTransactionResult> results2 = zkClient.startTransaction().create().forPath("/111")
                .and().create().forPath("/111/222")
                .and().create().forPath("/111/333")
//                .and().delete().forPath("/111/444")
                .and().commit();
        System.out.println(results2);
        return "okay!";
    }
}
